package cn.zyjw.controller;

import cn.zyjw.domain.User;
import cn.zyjw.dto.UserDto;
import cn.zyjw.feign.UserServiceFeign;
import cn.zyjw.mappers.UserDtoMapper;
import cn.zyjw.model.IdCardForm;
import cn.zyjw.model.R;
import cn.zyjw.service.UserService;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;

@RestController
@Api("用户中心")
@RequestMapping("/users")
public class UserController implements UserServiceFeign {

    @Autowired
    private UserService userService;

    @GetMapping
    @ApiOperation("列表分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页展示条数"),
            @ApiImplicitParam(name = "userId", value = "用户id"),
            @ApiImplicitParam(name = "userName", value = "用户名"),
            @ApiImplicitParam(name = "realName", value = "姓名"),
            @ApiImplicitParam(name = "mobile", value = "手机号"),
            @ApiImplicitParam(name = "status", value = "状态"),
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<Page<User>> findByPage(@ApiIgnore Page<User> page, Long userId, String userName, String realName, String mobile, Integer status) {

        page.addOrder(OrderItem.desc("last_update_time"));
        Page<User> userPage = userService.page(
                page,
                new LambdaQueryWrapper<User>()
                        .eq(userId != null, User::getId, userId)
                        .like(StringUtils.isNotBlank(userName), User::getUsername, userName)
                        .like(StringUtils.isNotBlank(realName), User::getRealName, realName)
                        .like(StringUtils.isNotBlank(mobile), User::getMobile, mobile)
                        .eq(status != null, User::getStatus, status)
        );
        return R.ok(userPage);
    }


    @PostMapping("/status")
    @ApiOperation("修改用户状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id"),
            @ApiImplicitParam(name = "status", value = "账户状态"),
    })
    public R<String> updStatus(@RequestParam Long id, @RequestParam Byte status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        boolean b = userService.updateById(user);
        if (b) {
            return R.ok(null, "修改成功");
        }
        return R.fail("修改失败");
    }

    @PatchMapping
    @ApiOperation("编辑用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户Json对象"),
    })
    public R upd(@RequestBody @Validated User user) {
        boolean b = userService.updateById(user);
        if (b) {
            return R.ok(null, "修改成功");
        }
        return R.fail("修改失败");
    }

    @GetMapping("/info")
    @ApiOperation("查询用户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long")
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<User> info(@RequestParam Long id) {
        User user = userService.getById(id);
        return R.ok(user);
    }

    @GetMapping("/current/info")
    @ApiOperation("获取登录用户账号信息")
    public R<User> currentUserInfo() {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        User user = userService.getById(Long.valueOf(userId));
        user.setPassword("******");
        user.setPaypassword("******");
        return R.ok(user);
    }

    @PostMapping("/authAccount")
    @ApiOperation("身份认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idCardForm", value = "身份认证数据")
    })
    public R<String> authAccount(@RequestBody @Validated IdCardForm idCardForm) {
        String userIdStr = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        Boolean isOk = userService.authAccount(Long.valueOf(userIdStr), idCardForm);
        if (isOk) {
            return R.ok("认证成功");
        }
        return R.fail("认证失败");
    }

    @PostMapping("/authUser")
    @ApiOperation("用户进行高级认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imgs", value = "证件照片数组")
    })
    public R authUser(@RequestBody String[] imgs) {
        String userIdStr = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        Boolean isOk = userService.authUser(Long.valueOf(userIdStr), imgs);
        if (isOk) {
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public List<UserDto> getBasicUsers(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<User> list = userService.list(
                new LambdaQueryWrapper<User>()
                        .in(User::getId, ids)
        );
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return UserDtoMapper.INSTANCE.convert2Dto(list);
    }
}
